package com.stuffthathappens.concurrency.ThreadBug;

/**
 * Demonstrates that on multi-core or multi-cpu systems, count++ is not an
 * atomic operation.
 *
 * @author Eric M. Burke
 */
public class ThreadBug extends Thread {
    public static final int NUM_THREADS = 100;
    public static final int NUM_ITERATIONS = 1000;

    public static long count;

    public static void main(String[] args) throws InterruptedException {
        ThreadBug[] updaters = new ThreadBug[NUM_THREADS];
        for (int i=0; i<updaters.length; i++) {
            updaters[i] = new ThreadBug();
            updaters[i].start();
        }
        // wait for all to finish
        for (ThreadBug updater : updaters) {
            updater.join();
        }

        System.out.println("Expected count: " + (NUM_THREADS * NUM_ITERATIONS));
        System.out.println("Actual count: " + count);
    }

    public void run() {
        for (int i=0; i<ThreadBug.NUM_ITERATIONS; i++) {
            // threading bug right here:
            ThreadBug.count++;
            if (i % 50 == 0) {
                Thread.yield();
            }
        }
    }
}


